<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getUserList, assignUserDepartment, getDepartmentOptions, activateUser } from '@/api/index.js';
import useUserInfoStore from '@/store/user.js';

// 添加防抖功能
const debounce = (fn, delay) => {
  let timeoutId
  return (...args) => {
    clearTimeout(timeoutId)
    timeoutId = setTimeout(() => fn.apply(null, args), delay)
  }
}

const store = useUserInfoStore();
const loading = ref(false);
const users = ref([]);
const departments = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const searchText = ref('');

// 用户类型映射表
const userTypeMap = {
  'ADMIN': '管理员',
  'TESTER': '测试员',
  'DEVELOPER': '开发人员',
  'MANAGER': '测试管理员',
  'VIEWER': '报告查看者'
};

// 分配部门和员工编号的对话框
const assignDialogVisible = ref(false);
const assignForm = reactive({
  id: null,
  username: '',
  department: null,
  employee_id: ''
});

// 检查是否有管理权限
const hasManagePermission = () => {
  return store.userInfo?.user_type === 'ADMIN' || store.userInfo?.user_type === 'MANAGER';
};

// 检查是否可以禁用用户
const canDisableUser = (user) => {
  // 如果用户未激活，总是可以激活
  if (!user.is_active) {
    return true;
  }
  
  // 不能禁用管理员和测试管理员
  if (user.user_type === 'ADMIN' || user.user_type === 'MANAGER') {
    return false;
  }
  
  // 不能禁用当前登录用户
  if (user.username === store.userInfo?.username) {
    return false;
  }
  
  return true;
};

// 获取禁用提示信息
const getDisableTooltip = (user) => {
  if (user.user_type === 'ADMIN' || user.user_type === 'MANAGER') {
    return '管理员账号不能被禁用';
  }
  
  if (user.username === store.userInfo?.username) {
    return '不能禁用当前登录的账号';
  }
  
  return '';
};

// 获取用户列表
const fetchUsers = async () => {
  try {
    loading.value = true;
    const params = {
      page: currentPage.value,
      page_size: pageSize.value,
      search: searchText.value
    };
    
    const res = await getUserList(params);
    if (res.status === 200) {
      users.value = res.data.users;
      total.value = res.data.total;
    } else {
      ElMessage.error(res.msg || '获取用户列表失败');
    }
  } catch (error) {
    console.error('获取用户列表出错:', error);
    ElMessage.error('网络错误，请稍后再试');
  } finally {
    loading.value = false;
  }
};

// 获取部门选项
const fetchDepartments = async () => {
  try {
    const res = await getDepartmentOptions();
    if (res.status === 200) {
      departments.value = res.data;
    }
  } catch (error) {
    console.error('获取部门列表出错:', error);
  }
};

// 生成员工编号
const generateEmployeeId = () => {
  if (!assignForm.department) {
    ElMessage.warning('请先选择部门');
    return;
  }
  
  // 找到选中的部门
  const selectedDept = departments.value.find(dept => dept.value === assignForm.department);
  if (!selectedDept) {
    ElMessage.error('未找到选中的部门');
    return;
  }
  
  // 生成格式：部门前缀 + 年月 + 4位随机数
  const now = new Date();
  const year = now.getFullYear().toString().substr(-2);
  const month = (now.getMonth() + 1).toString().padStart(2, '0');
  const random = Math.floor(Math.random() * 9000) + 1000; // 1000-9999
  
  // 简单的部门前缀映射
  const deptPrefix = selectedDept.label.substr(0, 2).toUpperCase();
  
  assignForm.employee_id = `${deptPrefix}${year}${month}${random}`;
};

// 添加防抖搜索
const debouncedSearch = debounce(() => {
  currentPage.value = 1
  fetchUsers()
}, 500)

const handleInputSearch = () => {
  debouncedSearch()
}

// 搜索用户
const handleSearch = () => {
  currentPage.value = 1;
  fetchUsers();
};

// 分页处理
const handlePageChange = (page) => {
  currentPage.value = page;
  fetchUsers();
};

const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
  fetchUsers();
};

// 打开分配对话框
const openAssignDialog = (user) => {
  assignForm.id = user.id;
  assignForm.username = user.username;
  assignForm.department = user.department || null;
  assignForm.employee_id = user.employee_id || '';
  assignDialogVisible.value = true;
};

// 提交分配
const submitAssign = async () => {
  try {
    const data = {
      department_id: assignForm.department,
      employee_id: assignForm.employee_id
    };
    
    const res = await assignUserDepartment(assignForm.id, data);
    if (res.status === 200) {
      ElMessage.success('分配成功');
      assignDialogVisible.value = false;
      // 刷新用户列表
      fetchUsers();
    } else {
      ElMessage.error(res.msg || '分配失败');
    }
  } catch (error) {
    console.error('分配部门和员工编号出错:', error);
    ElMessage.error('网络错误，请稍后再试');
  }
};

// 激活/禁用用户
const handleActivateUser = async (user) => {
  const action = user.is_active ? '禁用' : '激活';
  
  // 前端安全检查 - 只在禁用时检查
  if (user.is_active && (user.user_type === 'ADMIN' || user.user_type === 'MANAGER')) {
    ElMessage.error('不能禁用管理员或测试管理员账号');
    return;
  }
  
  // 检查是否是当前用户 - 只在禁用时检查
  if (user.is_active && user.username === store.userInfo?.username) {
    ElMessage.error('不能禁用当前登录的账号');
    return;
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要${action}用户"${user.username}"吗？`,
      `确认${action}`,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    
    const res = await activateUser(user.id, { is_active: !user.is_active });
    if (res.status === 200) {
      ElMessage.success(res.msg || `${action}成功`);
      fetchUsers(); // 刷新用户列表
    } else {
      ElMessage.error(res.msg || `${action}失败`);
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error(`${action}用户出错:`, error);
      ElMessage.error('网络错误，请稍后再试');
    }
  }
};

// 查看用户详情
const viewUserDetails = (user) => {
  const formatDateSafe = (dateString) => {
    if (!dateString) return '从未'
    try {
      return new Date(dateString).toLocaleString()
    } catch (error) {
      return '无效时间'
    }
  }

  ElMessageBox.alert(
    `<div style="text-align: left;">
      <p><strong>用户名：</strong>${user.username}</p>
      <p><strong>邮箱：</strong>${user.email}</p>
      <p><strong>手机号：</strong>${user.phone_number}</p>
      <p><strong>用户类型：</strong>${userTypeMap[user.user_type]}</p>
      <p><strong>部门：</strong>${user.department_name || '未设置'}</p>
      <p><strong>员工编号：</strong>${user.employee_id || '未设置'}</p>
      <p><strong>状态：</strong>${user.is_active ? '激活' : '禁用'}</p>
      <p><strong>注册时间：</strong>${formatDateSafe(user.date_joined)}</p>
      <p><strong>最后登录：</strong>${formatDateSafe(user.last_login)}</p>
    </div>`,
    `用户详情 - ${user.username}`,
    {
      confirmButtonText: '关闭',
      dangerouslyUseHTMLString: true,
      customStyle: {
        width: '500px'
      }
    }
  );
};
onMounted(() => {
  if (!hasManagePermission()) {
    ElMessage.error('只有管理员和测试管理员可以访问此页面');
    return;
  }
  fetchUsers();
  fetchDepartments();
});
</script>

<template>
  <div class="admin-user-management">
    <!-- 权限检查 -->
    <div v-if="!hasManagePermission()" class="no-permission">
      <el-result icon="warning" title="权限不足" sub-title="只有管理员和测试管理员可以访问此页面">
        <template #extra>
          <el-button type="primary" @click="$router.back()">返回</el-button>
        </template>
      </el-result>
    </div>

    <!-- 管理员界面 -->
    <div v-else class="management-container">
      <el-card class="management-card">
        <template #header>
          <div class="card-header">
            <div class="header-left">
              <h2>用户管理</h2>
              <p class="header-subtitle">管理系统中的所有用户，分配部门和员工编号</p>
            </div>
            <div class="search-container">
              <el-input
                v-model="searchText"
                placeholder="搜索用户名、邮箱或手机号"
                clearable
                @input="handleInputSearch"
                style="width: 300px; margin-right: 10px;"
              />
            </div>
          </div>
        </template>

        <!-- 用户列表表格 -->
        <el-table :data="users" v-loading="loading" stripe>
          <el-table-column prop="id" label="ID" width="60" />
          <el-table-column prop="username" label="用户名" width="120" />
          <el-table-column prop="email" label="邮箱" width="180" />
          <el-table-column prop="phone_number" label="手机号" width="120" />
          <el-table-column label="用户类型" width="120">
            <template #default="scope">
              <el-tag :type="scope.row.user_type === 'ADMIN' ? 'danger' : 'primary'">
                {{ userTypeMap[scope.row.user_type] || scope.row.user_type }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="department_name" label="部门" width="120">
            <template #default="scope">
              <span>{{ scope.row.department_name || '未设置' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="employee_id" label="员工编号" width="120">
            <template #default="scope">
              <span>{{ scope.row.employee_id || '未设置' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="80">
            <template #default="scope">
              <el-tag :type="scope.row.is_active ? 'success' : 'danger'">
                {{ scope.row.is_active ? '激活' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="注册时间" width="160">
            <template #default="scope">
              {{ scope.row.date_joined ? new Date(scope.row.date_joined).toLocaleString() : '-' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button
                type="primary"
                size="small"
                @click="openAssignDialog(scope.row)"
              >
                分配部门
              </el-button>
              <el-button
                v-if="canDisableUser(scope.row)"
                :type="scope.row.is_active ? 'warning' : 'success'"
                size="small"
                @click="handleActivateUser(scope.row)"
              >
                {{ scope.row.is_active ? '禁用' : '激活' }}
              </el-button>
              <el-tooltip 
                v-else
                :content="getDisableTooltip(scope.row)"
                placement="top"
              >
                <el-button
                  :type="scope.row.is_active ? 'warning' : 'success'"
                  size="small"
                  disabled
                >
                  {{ scope.row.is_active ? '禁用' : '激活' }}
                </el-button>
              </el-tooltip>
              <el-button
                type="info"
                size="small"
                link
                @click="viewUserDetails(scope.row)"
              >
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 分配部门和员工编号对话框 -->
    <el-dialog
      v-model="assignDialogVisible"
      title="分配部门和员工编号"
      width="500px"
    >
      <el-form :model="assignForm" label-width="100px">
        <el-form-item label="用户名：">
          <el-input v-model="assignForm.username" disabled />
        </el-form-item>
        <el-form-item label="部门：">
          <el-select
            v-model="assignForm.department"
            placeholder="请选择部门"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="dept in departments"
              :key="dept.value"
              :label="dept.label"
              :value="dept.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="员工编号：">
          <div style="display: flex; gap: 10px;">
            <el-input v-model="assignForm.employee_id" placeholder="请输入员工编号" />
            <el-button type="primary" @click="generateEmployeeId">自动生成</el-button>
          </div>
          <small style="color: #909399; font-size: 12px;">
            点击"自动生成"可根据所选部门自动生成员工编号
          </small>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="assignDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAssign">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="less" scoped>
.admin-user-management {
  padding: 20px;
  
  .no-permission {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 400px;
  }
  
  .management-container {
    max-width: 1200px;
    margin: 0 auto;
  }
  
  .management-card {
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      
      .header-left {
        flex: 1;
        
        h2 {
          margin: 0 0 5px 0;
          font-size: 20px;
          color: #333;
        }
        
        .header-subtitle {
          margin: 0;
          font-size: 14px;
          color: #666;
        }
      }
      
      .search-container {
        display: flex;
        align-items: center;
        flex-shrink: 0;
      }
    }
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
  
  .dialog-footer {
    text-align: right;
  }
}
</style>